from datetime import datetime
from app.Pojo.BClassification import  BClassification
from sqlalchemy import func


class ClassificationMapper:
    def __init__(self, db):
        self.db = db

    def list_classifications(self, page, page_size):
        """分页查询分类"""
        query = BClassification.query
        total = query.count()
        classifications = query.order_by(BClassification.create_time.desc()) \
            .limit(page_size) \
            .offset((page - 1) * page_size) \
            .all()
        return classifications, total

    def get_by_id(self, id):
        """根据ID获取分类"""
        return BClassification.query.get(id)

    def create_classification(self, classification):
        """新增分类"""
        self.db.session.add(classification)
        self.db.session.commit()
        return classification

    def update_classification(self, classification):
        """更新分类"""
        classification.update_time = datetime.utcnow()
        self.db.session.commit()
        return classification

    def delete_classifications(self, ids):
        """批量删除分类"""
        BClassification.query.filter(BClassification.id.in_(ids)).delete(synchronize_session=False)
        self.db.session.commit()

    def delete_classification(self, id):
        """删除分类"""
        BClassification.query.filter_by(id=id).delete(synchronize_session=False)
        self.db.session.commit()